﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;

namespace RandomPersonGetter
{
    class Program
    {
        static List<string> AllOfThePeople = new List<string>();
        static Random rand = new Random();
        static void Main()
        {
            do
            {
                CreateList();
                do
                {
                    int indexOfPerson = rand.Next(0, AllOfThePeople.Count);
                    string person = AllOfThePeople[indexOfPerson];
                    AllOfThePeople.Remove(person);
                    if (AllOfThePeople.Contains(person))
                    {
                        int chances = (AllOfThePeople.LastIndexOf(person) - AllOfThePeople.IndexOf(person)) + 1;
                        Console.WriteLine(person + " has only " + chances.ToString() + ((chances == 1) ? " chance left." : " chances left."));
                    }
                    else
                        Console.WriteLine(person + " is out.");
                } while (AllOfThePeople.Count > 1);

                Console.WriteLine(AllOfThePeople[0] + " is the winner!");
                Console.WriteLine("Again? y/n:");

            } while (Console.ReadLine().ToLower() == "y");
        }

        private static void CreateList()
        {
            XmlDocument listOfPeople = new XmlDocument();
            listOfPeople.Load("People.xml");

            XmlNode People = listOfPeople.SelectSingleNode("ListOfPeople");
            foreach (XmlNode Person in People.SelectNodes("Person"))
            {
                foreach (XmlNode Chances in Person.SelectNodes("Chances"))
                {
                    try
                    {
                        int TimesToAdd = int.Parse(Chances.InnerText);
                        for (int i = 0; i < TimesToAdd; i++)
                            AllOfThePeople.Add(Person.Attributes["id"].Value);
                    }
                    catch (FormatException)
                    {
                        Console.WriteLine("There's an error in your XML document. Chances must be a number.");
                        Console.WriteLine("Check the entry for {0} until then I'm ignoring {0}.", Person.Attributes["id"].Value);
                    }
                }
            }
        }
    }
}
